package com.jmcgg.freesky.common.util;

import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * Title: FreeSky Common Java Library <br>
 * Description: FreeSky Common Java Library <br>
 * Copyright: Copyright (c) 2005~2009 www.afss.cn <br>
 * Company: Amei's FreeSky Studio <br>
 * 
 * @author <b>Jacky Chou</b> (AFSS [Amei's FreeSky Studio])
 * @version 1.2.1, 2008-08-05, Clean and optimize the source code.<br>
 *          1.2.0, 2008-02-23, Upgrade freesky.jar to 1.2.0 with Struts 2<br>
 *          1.0.0, 2006-05-30, Initial Version
 */
public class ImageUtil extends FreeskyUtil {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ImageUtil.class);

	public static int DEST_WIDTH = 100;
	public static int DEST_HEIGHT = 100;

	public ImageUtil() {
	}

	public static void getProperty(File imageFile) {
		try {
			Image src = javax.imageio.ImageIO.read(imageFile); // 构造Image对象
			DEST_WIDTH = src.getWidth(null); // 得到源图宽
			DEST_HEIGHT = src.getHeight(null); // 得到源图长
		} catch (Exception e) {
			logger.error("getProperty(File) - File imageFile=" + imageFile, e);
		}
	}

	/**
	 * 生成缩略图。其实这个方法可以看作简单地对图片进行重新设置大小
	 * 
	 * @param inFileName
	 *            String 输入的图片文件名称（包含路径）
	 * @param outFileName
	 *            String 输出的图片文件名称（包含路径）
	 * @param destWidth
	 *            int 目标图片的宽度
	 * @param destHeight
	 *            int 目标图片的高度
	 * @return boolean 返回true表示成功；返回false表示失败。
	 */
	public static boolean createAbbJPEG(String inFileName, String outFileName,
			int destWidth, int destHeight) {
		if (destWidth == -1 && destHeight == -1) {
			return false;
		}
		try {
			// System.out.println(inFileName);
			// System.out.println(outFileName);
			File _file = new File(inFileName); // 读入文件
			Image src = javax.imageio.ImageIO.read(_file); // 构造Image对象
			int srcWidth = src.getWidth(null); // 得到源图宽
			int srcHeight = src.getHeight(null); // 得到源图长
			if (destHeight == -1) {
				destHeight = (int) (destWidth * srcHeight / srcWidth);
			} else if (destWidth == -1) {
				destWidth = (int) (destHeight * srcWidth / srcHeight);
			}
			DEST_WIDTH = destWidth;
			DEST_HEIGHT = destHeight;

			BufferedImage tag = new BufferedImage(destWidth, destHeight,
					BufferedImage.TYPE_INT_RGB);
			tag.getGraphics().drawImage(src, 0, 0, destWidth, destHeight, null); // 绘制缩小后的图
			FileOutputStream out = new FileOutputStream(outFileName); // 输出到文件流
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			encoder.encode(tag); // 近JPEG编码
			out.close();
			return true;
		} catch (Exception e) {
			logger.error(
					"createAbbJPEG(String, String, int, int) - String inFileName="
							+ inFileName + ", String outFileName="
							+ outFileName + ", int destWidth=" + destWidth
							+ ", int destHeight=" + destHeight, e);

			return false;
		}
	}

	/**
	 * 生成缩略图。其实这个方法可以看作简单地对图片进行重新设置大小
	 * 
	 * @param inFile
	 *            String 输入的图片文件
	 * @param outFileName
	 *            String 输出的图片文件（包含路径）
	 * @param destWidth
	 *            int 目标图片的宽度
	 * @param destHeight
	 *            int 目标图片的高度
	 * @return boolean 返回true表示成功；返回false表示失败。
	 */
	@SuppressWarnings("restriction")
	public static boolean createAbbJPEG(File inFile, String outFileName,
			int destWidth, int destHeight) {
		if (destWidth == -1 && destHeight == -1) {
			return false;
		}
		try {
			Image src = javax.imageio.ImageIO.read(inFile); // 构造Image对象
			int srcWidth = src.getWidth(null); // 得到源图宽
			int srcHeight = src.getHeight(null); // 得到源图长
			if (destHeight == -1) {
				destHeight = (int) (destWidth * srcHeight / srcWidth);
			} else if (destWidth == -1) {
				destWidth = (int) (destHeight * srcWidth / srcHeight);
			}
			DEST_WIDTH = destWidth;
			DEST_HEIGHT = destHeight;

			BufferedImage tag = new BufferedImage(destWidth, destHeight,
					BufferedImage.TYPE_INT_RGB);
			tag.getGraphics().drawImage(src, 0, 0, destWidth, destHeight, null); // 绘制缩小后的图
			FileOutputStream out = new FileOutputStream(outFileName); // 输出到文件流
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			encoder.encode(tag); // 近JPEG编码
			out.close();
			return true;
		} catch (Exception e) {
			logger.error(
					"createAbbJPEG(File, String, int, int) - String outFileName="
							+ outFileName + ", int destWidth=" + destWidth
							+ ", int destHeight=" + destHeight, e);

			return false;
		}
	}

	public static void main(String[] args) {
		int width = 130;
		int height = -1;
		ImageUtil.createAbbJPEG("E:/Temp/watch/A-K003.jpg",
				"E:/Temp/watch/A-K003_s1.jpg", width, height);
		ImageUtil.createAbbJPEG("E:/Temp/watch/A-S004.jpg",
				"E:/Temp/watch/A-S004_s1.jpg", width, height);
		ImageUtil.createAbbJPEG("E:/Temp/watch/A-SZ011.jpg",
				"E:/Temp/watch/A-SZ011_s1.jpg", width, height);
		ImageUtil.createAbbJPEG("E:/Temp/watch/A-SZ017.jpg",
				"E:/Temp/watch/A-SZ017_s1.jpg", width, height);

		ImageUtil.createThumbnail("E:/Temp/watch/A-K003.jpg",
				"E:/Temp/watch/A-K003_s2.jpg", width, height);
		ImageUtil.createThumbnail("E:/Temp/watch/A-S004.jpg",
				"E:/Temp/watch/A-S004_s2.jpg", width, height);
		ImageUtil.createThumbnail("E:/Temp/watch/A-SZ011.jpg",
				"E:/Temp/watch/A-SZ011_s2.jpg", width, height);
		ImageUtil.createThumbnail("E:/Temp/watch/A-SZ017.jpg",
				"E:/Temp/watch/A-SZ017_s2.jpg", width, height);
		System.out.println("Finish!");
	}

	// 上传图片的缩放处理
	// 图片上传到服务器后,会根据情况将图片缩小成一个图标,我们可以利用java强大的图形处理功能,对上传的图片进行缩放处理.
	// 下面的程序使用jdk1.4中最新的ImageIO对图片进行读写.使用AffineTransform对图片进行缩放.

	public static boolean createThumbnail(String inFileName,
			String outFileName, int outWidth, int outHeight) {
		try {
			double Ratio = 0.0;
			File inFile = new File(inFileName);
			if (!inFile.isFile()) {
				logger.error(inFile
						+ " is not image file error in CreateThumbnail!");
				return false;
			}
			File outFile = new File(outFileName);
			BufferedImage src = javax.imageio.ImageIO.read(inFile);
			int srcWidth = src.getWidth(null); // 得到源图宽
			int srcHeight = src.getHeight(null); // 得到源图长
			if (outHeight == -1) {
				outHeight = (int) (outWidth * srcHeight / srcWidth);
			} else if (outWidth == -1) {
				outWidth = (int) (outHeight * srcWidth / srcHeight);
			}
			DEST_WIDTH = outWidth;
			DEST_HEIGHT = outHeight;

			Image Itemp = src.getScaledInstance(outWidth, outHeight,
					BufferedImage.TYPE_INT_RGB);

			if ((srcHeight > outHeight) || (srcWidth > outWidth)) {
				Ratio = (outWidth * 1.0 / srcWidth);
			}
			AffineTransformOp op = new AffineTransformOp(
					AffineTransform.getScaleInstance(Ratio, Ratio), null);
			Itemp = op.filter(src, null);

			ImageIO.write((BufferedImage) Itemp, "jpg", outFile);
			return true;
		} catch (Exception e) {
			logger.error(
					"createThumbnail(String, String, int, int) - String inFileName="
							+ inFileName + ", String outFileName="
							+ outFileName + ", int outWidth=" + outWidth
							+ ", int outHeight=" + outHeight, e);
		}
		return false;
	}
}
